package com.devplatform.service.impl.article;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.devplatform.mapper.article.ArticleInteractionsMapper;
import com.devplatform.pojo.article.ArticleInteractions;
import com.devplatform.service.article.ArticleInteractionsService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Jnks03
 * @description 针对表【article_interactions】的数据库操作Service实现
 * @createDate 2025-09-29 09:51:53
 */
@Service
@RequiredArgsConstructor
public class ArticleInteractionsServiceImpl extends ServiceImpl<ArticleInteractionsMapper, ArticleInteractions>
        implements ArticleInteractionsService {
    private final ArticleInteractionsMapper interactionsMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementViewCount(Long articleId) {
        ArticleInteractions interactions = this.getByArticleId(articleId);
        if (interactions != null) {
            interactions.setViewCount(interactions.getViewCount() + 1);
            return interactionsMapper.updateById(interactions) > 0;
        }
        return false;
    }

    @Override
    public void initArticleInteractions(Long articleId) {
        // 检查是否已存在互动记录（避免重复插入）
        ArticleInteractions existing = this.getByArticleId(articleId);
        if (existing == null) {
            ArticleInteractions interactions = new ArticleInteractions();
            interactions.setArticleId(articleId);
            // 初始化所有计数为0
            interactions.setViewCount(0);
            interactions.setLikeCount(0);
            interactions.setCommentCount(0);
            interactions.setCollectCount(0);
            interactions.setShareCount(0);
            interactions.setArticlePoints(0);
            // 插入数据库
            this.save(interactions);
        }
    }

    @Override
    public ArticleInteractions getByArticleId(Long articleId) {
        LambdaQueryWrapper<ArticleInteractions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ArticleInteractions::getArticleId, articleId);
        return baseMapper.selectOne(queryWrapper);
    }
}




